<template>
  <div class="main">
    <div class="login-body">
      <div class="pic"></div>
      <div class="form">
        <div class="login-header">
          <h1>星尘商场购物系统</h1>
          <p>开启您的购物之旅</p>
        </div>
        <el-form :model="loginFormModel" :rules="rules" ref="loginFormRef" class="login-form">
          <el-row>
            <el-col :span="24">
              <el-form-item label="用户名:" prop="username" :label-width="80">
                <el-input
                    v-model="loginFormModel.username"
                    placeholder="用户名"
                    class="custom-input"
                    autocomplete="off"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="密码:" prop="password" :label-width="80">
                <el-input
                    type="password"
                    v-model="loginFormModel.password"
                    show-password
                    placeholder="请输入密码"
                    class="custom-input"
                    autocomplete="off"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-button
                  type="primary"
                  class="login-btn"
                  @click="submitLogin"
                  :loading="isLoading"
              >
                <span v-if="!isLoading">登&nbsp;&nbsp;录</span>
                <span v-else><el-icon><Loading /></el-icon> 登录中...</span>
              </el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" class="link-group">
              <a href="#" class="link" @click="mess">忘记密码?</a>
              <a href="#" class="link" @click="openRegisterDialog">注册账号</a>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="mask"></div>
    <div class="copyright">
      <h2>&copy;版权所有 星尘商场购物系统</h2>
    </div>

    <!-- 注册弹窗 -->
    <el-dialog
        title="用户注册"
        v-model="registerDialogVisible"
        width="400px"
        :close-on-click-modal="false"
        :before-close="handleClose"
    >
      <el-form
          :model="registerForm"
          :rules="registerRules"
          ref="registerFormRef"
          label-width="80px"
          class="register-form"
      >
        <el-form-item label="用户名:" prop="name">
          <el-input
              v-model="registerForm.name"
              placeholder="请输入用户名"
              autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="手机号:" prop="phone">
          <el-input
              v-model="registerForm.phone"
              placeholder="请输入手机号"
              autocomplete="off"
              maxlength="11"
          />
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input
              type="password"
              v-model="registerForm.password"
              show-password
              placeholder="请输入密码"
              autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="确认密码:" prop="confirmPassword">
          <el-input
              type="password"
              v-model="registerForm.confirmPassword"
              show-password
              placeholder="请再次输入密码"
              autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="registerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRegister" :loading="registerLoading">
          <span v-if="!registerLoading">注册</span>
          <span v-else><el-icon><Loading /></el-icon> 注册中...</span>
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.main {
  height: 100vh;
  background: url("@/assets/bg.png") no-repeat center center/cover;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.main > .mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(2px);
}

.login-body {
  width: 700px;
  height: 480px;
  background-color: #fff;
  display: flex;
  flex-direction: row;
  z-index: 1000;
  border-radius: 12px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  transition: all 0.3s ease;
}

.login-body:hover {
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.25);
  transform: translateY(-5px);
}

.login-body > .pic {
  width: 38%;
  background: url("@/assets/jo.png") no-repeat center center/cover;
  position: relative;
}

.login-body > .pic::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.login-body > .form {
  flex-grow: 1;
  padding: 40px 30px;
  box-sizing: border-box;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h1 {
  font-size: 28px;
  color: #16b777;
  margin-bottom: 8px;
  font-weight: 600;
  position: relative;
  display: inline-block;
}

.login-header h1::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 50%;
  transform: translateX(-50%);
  width: 50px;
  height: 3px;
  background-color: #16b777;
  border-radius: 3px;
}

.login-header p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.login-form {
  padding: 10px 20px;
}

.custom-input {
  height: 45px;
  border-radius: 6px;
  border-color: #e5e5e5;
  transition: all 0.3s ease;
}

.custom-input:focus-within {
  border-color: #16b777;
  box-shadow: 0 0 0 3px rgba(22, 183, 119, 0.1);
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  color: #555;
  font-weight: 500;
}

.login-btn {
  width: 100%;
  height: 50px;
  background-color: #16b777;
  color: #fff;
  font-size: 18px;
  border-radius: 6px;
  border: none;
  transition: all 0.3s ease;
}

.login-btn:hover {
  background-color: #13a066;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(22, 183, 119, 0.3);
}

.login-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(22, 183, 119, 0.2);
}

.copyright {
  position: fixed;
  bottom: 30px;
  color: #fff;
  font-size: 14px;
  text-align: center;
  z-index: 1000;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}

.link-group {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
  padding: 0 10px;
}

.link {
  color: #16b777;
  font-size: 14px;
  text-decoration: none;
  transition: all 0.2s ease;
}

.link:hover {
  color: #13a066;
  text-decoration: underline;
}

/* 注册表单样式补充 */
.register-form {
  margin-top: 10px;
}

.register-form .el-form-item {
  margin-bottom: 15px;
}
</style>

<script setup>
import { ref, reactive, toRaw } from "vue";
import { ElMessage, ElIcon } from "element-plus";
import { useRouter } from "vue-router";
import { login } from "@/api/user.js";
import { saveJwt } from "@/api/jwt.js";
import { Loading } from "@element-plus/icons-vue";
import api from "@/util/api.js";

// 忘记密码提示
function mess() {
  ElMessage.warning("请联系管理员修改密码！");
}

// 加载状态
const isLoading = ref(false);

// 表单验证规则
const rules = {
  username: [
    { required: true, message: "用户名不可为空", trigger: "blur" },
  ],
  password: [
    { required: true, message: "密码不可为空", trigger: "blur" },
  ],
};

// 登录数据模型
const loginFormModel = reactive({
  username: "admin0",
  password: "123456",
});

// 路由实例
const router = useRouter();
let loginFormRef = ref(); // 表单实例引用

// 提交登录
function submitLogin() {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      isLoading.value = true;
      try {
        let model = toRaw(loginFormModel);

        let resp = await login(model);
        if (resp.success) {
          saveJwt(resp.data);

          ElMessage.success("登录成功，正在跳转...");
          setTimeout(async () => {
            await router.push("/main/member");
          }, 800);
        } else {
          ElMessage.error(resp.error || "登录失败");
        }
      } catch (error) {
        ElMessage.error("网络异常，请稍后重试");
      } finally {
        isLoading.value = false;
      }
    } else {
      ElMessage.error("输入不合法");
    }
  });
}

// 注册相关功能实现
const registerDialogVisible = ref(false); // 注册弹窗显示状态
const registerLoading = ref(false); // 注册加载状态
const registerFormRef = ref(); // 注册表单引用

// 注册表单数据
const registerForm = reactive({
  name: "",
  phone: "",
  password: "",
  confirmPassword: "",
});

// 注册表单验证规则
const registerRules = {
  name: [
    { required: true, message: "用户名不可为空", trigger: "blur" },
    { min: 2, max: 10, message: "用户名长度在2-10个字符之间", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "手机号不可为空", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号格式", trigger: "blur" },
  ],
  password: [
    { required: true, message: "密码不可为空", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在6-20个字符之间", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 打开注册弹窗
function openRegisterDialog() {
  registerDialogVisible.value = true;
  // 重置表单
  registerFormRef.value?.resetFields();
}

// 关闭弹窗回调
function handleClose() {
  registerDialogVisible.value = false;
}

// 提交注册
async function submitRegister() {
  registerFormRef.value.validate(async (valid) => {
    if (valid) {
      registerLoading.value = true;
      try {
        // 准备提交数据（过滤确认密码字段）
        const formData = {
          name: registerForm.name,
          phone: registerForm.phone,
          password: registerForm.password,
        };
        console.log(formData);
        // 调用注册接口
        const res = await api.post("/users/save", formData);
        console.log(res);
        if (res.success) {
          ElMessage.success("注册成功，请登录！");
          registerDialogVisible.value = false;
          // 自动填充手机号到登录表单
          loginFormModel.username = registerForm.phone;
        } else {
          ElMessage.error(res.msg || "注册失败，请稍后重试");
        }
      } catch (error) {
        console.error("注册接口调用失败", error);
        ElMessage.error("网络异常，注册失败");
      } finally {
        registerLoading.value = false;
      }
    }
  });
}
</script>